//
//  STAlignmentFlowLayout.m
//  YiYueStore
//
//  Created by zhouzhouzhou on 2018/10/26.
//  Copyright © 2018年 YuYiLian. All rights reserved.
//

#import "STAlignmentFlowLayout.h"

@implementation STAlignmentFlowLayout
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
    // 获取系统帮我们计算好的Attributes
    if (self.spaceNum == 0 || !self.spaceNum) {
        return  [super layoutAttributesForElementsInRect:rect];
    }
    NSArray *answer = [super layoutAttributesForElementsInRect:rect];
    
    // 遍历结果
    for(int i = 0; i < [answer count]; ++i) {
        
        // 获取cell的Attribute，根据上一个cell获取最大的x，定义为origin
        UICollectionViewLayoutAttributes *currentAttr = answer[i];
        UICollectionViewLayoutAttributes *previousAttr = i == 0 ? nil : answer[i-1];
        UICollectionViewLayoutAttributes *nextAttr = i + 1 == answer.count ? nil : answer[i+1];
        CGFloat previousY = previousAttr == nil ? 0 : CGRectGetMaxY(previousAttr.frame);
        CGFloat currentY = CGRectGetMaxY(currentAttr.frame);
        CGFloat nextY = nextAttr == nil ? 0 : CGRectGetMaxY(nextAttr.frame);
        if (currentY != previousY && currentY != nextY){
            if ([currentAttr.representedElementKind isEqualToString:UICollectionElementKindSectionHeader]) {
            }else if ([currentAttr.representedElementKind isEqualToString:UICollectionElementKindSectionFooter]){
            }else{
            }
        }else if( currentY != nextY) {//如果下一个cell在本行，这开始调整Frame位置
//
            NSInteger origin =  CGRectGetMaxX(previousAttr.frame); ;

            // 设置cell最大间距
            NSInteger maximumSpacing = self.spaceNum;

            // 若当前cell和precell在同一行：①判断当前的cell加间距后的最大宽度是否小于ContentSize的宽度，②判断当前cell的x是否大于precell的x（否则cell会出现重叠）

            //满足则给当前cell的frame属性赋值（不满足的cell会根据系统布局换行）
            CGRect frame = currentAttr.frame;
            frame.origin.x = origin + maximumSpacing;
            currentAttr.frame = frame;
        }else if( currentY == previousY){
            NSInteger origin =  CGRectGetMaxX(previousAttr.frame); ;
            
            // 设置cell最大间距
            NSInteger maximumSpacing = self.spaceNum;
            
            // 若当前cell和precell在同一行：①判断当前的cell加间距后的最大宽度是否小于ContentSize的宽度，②判断当前cell的x是否大于precell的x（否则cell会出现重叠）
            
            //满足则给当前cell的frame属性赋值（不满足的cell会根据系统布局换行）
            CGRect frame = currentAttr.frame;
            frame.origin.x = origin + maximumSpacing;
            currentAttr.frame = frame;
        } 
    }
    return answer;
}

@end
